<!--
 * @Author: boyyang
 * @Date: 2022-01-11 11:56:47
 * @LastEditTime: 2022-02-21 16:11:51
 * @LastEditors: boyyang
 * @Description: 
 * @FilePath: \boyyang\src\components\upload\index.vue
-->

<template>
    <div :class="['upload', { 'upload-border': props.isBorder }]" @click="uploadClick">
        <img :src="imgMes.tempUrl" />
        <input
            type="file"
            id="upload"
            class="inner-upload"
            ref="upload"
            @change="fileChange"
            :accept="props.fileType"
        />
    </div>
</template>

<script lang="ts" setup>
import { useMessage } from '@/components/message'
import { getFileBlob } from '@/utils/getFileBlob'

interface IImgMes {
    tempUrl?: string;
    file?: File;
}

interface IUploadProps {
    size?: number; //头像大小 单位px
    fileSize?: number | string; //文件大小 单位MB
    fileType?: string; //上传文件类型 默认所有文件
    isBorder?: boolean; //是否有border 默认true
    borderWidth?: number; //border 宽度 2px
    borderColor?: string; //border 颜色
    autoUpload?: boolean; //是否自动上传
    action?: string; //自动上传地址
    headers?: object; //自动上传header
    imgUrl?: string; //头像访问链接
}

interface IUploadEmits {
    (e: 'onChange', fileMes: IImgMes): void
}

const message = useMessage()

const props = withDefaults(defineProps<IUploadProps>(), {
    size: 100,
    fileSize: '3',
    fileType: '*',
    isBorder: true,
    borderWidth: 2,
    borderColor: '#FFFFFF',
    autoUpload: false,
    imgUrl: ''
})

const emits = defineEmits<IUploadEmits>()

// input
const upload = ref<any>()

// 图片信息
const imgMes = reactive<IImgMes>({})

imgMes.tempUrl = props.imgUrl

// 点击盒子
const uploadClick = () => {
    upload.value.click()
}

// 文件发生变化
const fileChange = (e: any) => {

    const file = e.target.files[0] as File
    const url = getFileBlob(file)

    let size = file.size / 1024 / 1024

    if (size > props.fileSize) {
        message.error(`上传文件不能大于${props.fileSize}M`)
        return
    }

    imgMes.tempUrl = url
    imgMes.file = file

    // 将文件信息返回给外层组件函数
    emits('onChange', imgMes)
    // 自动上传
    autoUpload(file)
}

// 自动上传
const autoUpload = (file: File) => {
    if (props.autoUpload) {
        if (props.action !== '') {
            //接口上传逻辑    
        } else {
            message.error('自动上传地址为必填项')
        }
    }
}


</script>

<style scoped lang="scss">
.upload {
    box-sizing: border-box;
    width: calc(v-bind("props.size") * 1px);
    height: calc(v-bind("props.size") * 1px);
    background-color: rgb(68, 152, 185);
    border-radius: 100%;
    overflow: hidden;

    display: flex;
    justify-content: center;
    align-items: center;

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        // transform: scale(1.2);
    }

    .inner-upload {
        display: none;
    }
}

.upload-border {
    border: calc(v-bind("props.borderWidth") * 1px) solid
        v-bind("props.borderColor");
}
</style>
